package com.keya.pull;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.keya.base.exception.BusinessException;
import com.keya.device.Device;
import com.keya.device.DeviceProperties;
import com.keya.device.DeviceService;
import com.keya.features.tool.DicomNetParams;
import com.keya.features.tool.EchoSCU;
import io.micrometer.core.annotation.Timed;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @author huangshuqiang
 * @version 1.0
 * @description: TODO
 * @date 2022/8/31 14:01
 */
@RestController
@RequestMapping("/config")
@Timed("api_config")
public class PullController {
    @Resource
    private PublicParamService publicParamService;
//    @Resource
//    private DataSourceUtil dataSourceUtil;
    @Resource
    private DeviceService deviceService;
    @Resource
    private DeviceProperties deviceProperties;

    @ApiOperation(value = "查询数据源视图配置")
    @GetMapping("/datasource")
    public DatasourceConfigVO getDatasource() {
        DatasourceViewVO datasourceView = publicParamService.getDatasourceView();
        DatasourcePacsVO datasourcePacs = publicParamService.getDatasourcePacs();
        PullStudyCronVO pullStudy = publicParamService.getPullStudy();
        return new DatasourceConfigVO().mergeVo(datasourceView, datasourcePacs, pullStudy);
    }

    @ApiOperation(value = "保存数据源配置")
    @PostMapping("/datasource")
    public void saveDatasource(@RequestBody @Valid DatasourceConfigVO vo) throws Exception {
        vo.setName("study_view");
        DatasourceViewVO dsView = vo.genDatasourceViewVO();
        DatasourcePacsVO dsPACS = vo.genDatasourcePacsVO();
        if (Boolean.TRUE.equals(vo.getFindPacsEnabled())) {
            testDatasourcePacs(dsPACS);
        }
        if (Boolean.TRUE.equals(vo.getFindViewEnabled())) {
            testDatasourceView(dsView);
        }
        publicParamService.updateByKey(PublicParamKey.DATA_SOURCE_VIEW, JSONObject.toJSONString(dsView));
        publicParamService.updateByKey(PublicParamKey.DATA_SOURCE_PACS, JSONObject.toJSONString(dsPACS));

        PullStudyCronVO pullConfig = vo.genPullStudyCronVO();
        publicParamService.updateByKey(PublicParamKey.PULL_STUDY_CRON, JSONObject.toJSONString(pullConfig));
    }

    @ApiOperation(value = "测试数据源视图配置")
    @PostMapping("/datasource/view/test")
    public void testDatasourceView(@RequestBody @Valid DatasourceViewVO testVO) throws BusinessException {
        Integer deviceId = testVO.getDeviceId();
        if (deviceId == null) {
            throw new BusinessException(-1, "pacs设备id不能为空");
        }
        if (deviceService.count(new LambdaQueryWrapper<Device>().in(Device::getId, deviceId)) == 0) {
            throw new BusinessException(-1, "pacs设备id不存在");
        }
        if (StringUtils.isEmpty(testVO.getSql())) {
            throw new BusinessException(-1, "sql语句不能为空");
        }

        DatasourceViewVO vo = new DatasourceViewVO();
        vo.setName("test_study_view");
        try {
            BeanUtil.copyProperties(testVO, vo);
//            dataSourceUtil.loadDataSource(vo);
        } catch (Exception e) {
            throw new BusinessException(-1, "数据源配置异常");
        } finally {
//            dataSourceUtil.removeDataSource(vo.getName());
        }
    }

    @ApiOperation(value = "测试数据源pacs配置")
    @PostMapping("/datasource/pacs/test")
    public void testDatasourcePacs(@RequestBody DatasourcePacsVO vo) throws Exception {
        List<Integer> deviceIds = vo.getDeviceIds();
        if (deviceIds.isEmpty()) {
            throw new BusinessException(-1, "pacs设备id列表不能为空");
        }
        List<String> aeTitles = new ArrayList<>();
        if (deviceService.count(new LambdaQueryWrapper<Device>().in(Device::getId, deviceIds)) != deviceIds.size()) {
            throw new BusinessException(-1, "pacs设备列表数据异常");
        }
        for (Integer id : deviceIds) {
            Device device = deviceService.getById(id);
            int status = new EchoSCU().cEcho(new DicomNetParams(device.getAetitle(), device.getIp(), device.getPort(),
                    deviceService.getLocalHost().getAetitle(), deviceProperties.getPingTimeout() * 1000));
            if (status != 0) {
                aeTitles.add(device.getAetitle());
            }
        }
        if (aeTitles.size() != 0) {
            throw new BusinessException(-1, StringUtils.join(aeTitles, ",") + " 设备异常");
        }
    }
}
